//
//  AppDelegate+JPushDelegate.m
//  PeiZiWangBei
//
//  Created by 巨彦新 on 2017/12/28.
//  Copyright © 2017年 LK-IOS. All rights reserved.
//

#import "AppDelegate+JPushDelegate.h"
#import <UserNotifications/UserNotifications.h>
#import "YDBaseMessageViewController.h"
#import "YDBaseTabBarController.h"


#define JPush_AppKey_YouGuWang @"dd681eb80320aec2104954cc"

static char WindowKey;


@implementation AppDelegate (JPushDelegate)

-(UIWindow *)windows
{
    return objc_getAssociatedObject(self, &WindowKey);
}

-(void)setWindows:(UIWindow *)windows
{
    [self willChangeValueForKey:@"WindowKey"];
    objc_setAssociatedObject(self, &WindowKey,
                             windows,
                             OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    [self didChangeValueForKey:@"WindowKey"];
}

- (void)init_jpushWithOptions:(NSDictionary *)launchOptions window:(UIWindow *)window
{
    JPUSHRegisterEntity *entity = [[JPUSHRegisterEntity alloc] init];
    entity.types = JPAuthorizationOptionAlert|JPAuthorizationOptionBadge|JPAuthorizationOptionSound;
    [JPUSHService registerForRemoteNotificationConfig:entity delegate:self];
    
    self.windows = window;
    //如不需要使用IDFA，advertisingIdentifier 可为nil
    [JPUSHService setupWithOption:launchOptions
                           appKey:JPush_AppKey_YouGuWang
                          channel:@"App Store"
                 apsForProduction:FALSE
            advertisingIdentifier:nil];
    
    //2.1.9版本新增获取registration id block接口。
    [JPUSHService registrationIDCompletionHandler:^(int resCode, NSString *registrationID) {
        if(resCode == 0){
            
            //发送注册id到服务器
            NSLog(@"registrationID获取成功：%@",registrationID);
            
            [SYUserInformation sharedInstance].registrationID = registrationID;
            
            
            if (![[SYUserDataManger sharedInstance] userTokenIsOver]) {
                
                //上传极光ID
                [[SYVersionManger sharedInstance] upLoadJpushID];
            }

            
            
        }
        else{
            NSLog(@"registrationID获取失败，code：%d",resCode);
        }
    }];
}

-(void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
    [JPUSHService registerDeviceToken:deviceToken];
}


- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
   
    [JPUSHService handleRemoteNotification:userInfo];
    
    
    NSLog(@"iOS7及以上系统，收到通知:%@", [self logDic:userInfo]);
    
    if ([[UIDevice currentDevice].systemVersion floatValue]<10.0 || application.applicationState>0) {
        [self dealWithNoti];
        
    }
    
    completionHandler(UIBackgroundFetchResultNewData);
}



-(void)applicationDidEnterBackground:(UIApplication *)application
{
    [JPUSHService resetBadge];
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
    //DDLog(@"====%@",[JPUSHService registrationID]);
}

#pragma mark- JPUSHRegisterDelegate
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(NSInteger))completionHandler
{
    NSDictionary * userInfo = notification.request.content.userInfo;
//
//    UNNotificationRequest *request = notification.request; // 收到推送的请求
//    UNNotificationContent *content = request.content; // 收到推送的消息内容
//
//    NSNumber *badge = content.badge;  // 推送消息的角标
//    NSString *body = content.body;    // 推送消息体
//    UNNotificationSound *sound = content.sound;  // 推送消息的声音
//    NSString *subtitle = content.subtitle;  // 推送消息的副标题
//    NSString *title = content.title;  // 推送消息的标题
//
    
    if (@available(iOS 10.0, *)) {
        if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
            [JPUSHService handleRemoteNotification:userInfo];
            NSLog(@"iOS10 前台收到远程通知:%@", [self logDic:userInfo]);
            //处理跳转 气泡显示问题
            // [rootViewController addNotificationCount];
            
        }
        else {
            // 判断为本地通知
        }
        
        completionHandler(UNNotificationPresentationOptionBadge|UNNotificationPresentationOptionSound|UNNotificationPresentationOptionAlert); // 需要执行这个方法，选择是否提醒用户，有Badge、Sound、Alert三种类型可以设置
    } else {
        // Fallback on earlier versions
    }
    
}

- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)(void))completionHandler
{
    
    NSDictionary * userInfo = response.notification.request.content.userInfo;
//    UNNotificationRequest *request = response.notification.request; // 收到推送的请求
//    UNNotificationContent *content = request.content; // 收到推送的消息内容
//
//    NSNumber *badge = content.badge;  // 推送消息的角标
//    NSString *body = content.body;    // 推送消息体
//    UNNotificationSound *sound = content.sound;  // 推送消息的声音
//    NSString *subtitle = content.subtitle;  // 推送消息的副标题
//    NSString *title = content.title;  // 推送消息的标题
    
    if (@available(iOS 10.0, *)) {
        if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
            [JPUSHService handleRemoteNotification:userInfo];
            NSLog(@"iOS10 收到远程通知:%@", [self logDic:userInfo]);
            [self dealWithNoti];
        }
        else {
            // 判断为本地通知
           
        }
        
        completionHandler();  // 系统要求执行这个方法
    } else {
        // Fallback on earlier versions
    }
    
    
}

- (void)dealWithNoti
{
    if ([[SYUserDataManger sharedInstance] userTokenIsOver]) {return;};
    
    [[NSNotificationCenter defaultCenter] postNotificationName:kShowRedPointNoti object:@(YES) userInfo:nil];
    
    // 获取导航控制器
    YDBaseTabBarController *tabVC = (YDBaseTabBarController *)self.windows.rootViewController;
    //分栏选中我的页面
    
    YDBaseNavigationController *nav = (YDBaseNavigationController *)tabVC.viewControllers[tabVC.selectedIndex];
    [nav popViewControllerAnimated:NO];
    
    
    tabVC.selectedIndex = 3;
    
    YDBaseNavigationController *pushClassStance = (YDBaseNavigationController *)tabVC.viewControllers[tabVC.selectedIndex];
    
    
    //获取我的页面
    UIViewController *minevc = [pushClassStance.drj_viewControllers objectAtIndex:0];
    
    
    if (![minevc isKindOfClass:[YDBaseMessageViewController class]])
    {
        //当前显示界面非消息界面
        YDBaseMessageViewController *vc = [[YDBaseMessageViewController alloc] init];
        vc.hidesBottomBarWhenPushed = YES;
        [minevc.navigationController pushViewController:vc animated:YES];
    }
}

// log NSSet with UTF8
// if not ,log will be \Uxxx
- (NSString *)logDic:(NSDictionary *)dic {
    if (![dic count]) {
        return nil;
    }
    NSString *tempStr1 =
    [[dic description] stringByReplacingOccurrencesOfString:@"\\u"
                                                 withString:@"\\U"];
    NSString *tempStr2 =
    [tempStr1 stringByReplacingOccurrencesOfString:@"\"" withString:@"\\\""];
    NSString *tempStr3 =
    [[@"\"" stringByAppendingString:tempStr2] stringByAppendingString:@"\""];
    NSData *tempData = [tempStr3 dataUsingEncoding:NSUTF8StringEncoding];
    
//    [NSPropertyListSerialization propertyListFromData:tempData
//                                     mutabilityOption:NSPropertyListImmutable
//                                               format:NULL
//                                     errorDescription:NULL];
    
   NSString *str = [NSPropertyListSerialization propertyListWithData:tempData
                                                             options:NSPropertyListImmutable
                                                              format:NULL
                                                               error:NULL];
    
    return str;
}
@end
